import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from water_schedule import WATER_SCHEDULE
from utils import (
    generate_sound, 
    get_next_water_time, 
    get_formatted_time,
    analyze_body_data
)
import pystray
from PIL import Image
import os

class WaterReminder:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('饮水小贴士')
        icon_path = os.path.join(os.path.dirname(__file__), 'assets', 'icon.ico')
        self.root.iconbitmap(icon_path)
        # 设置窗口大小和位置
        self.window_width = 250
        self.window_height = 100
        self.root.geometry(f'{self.window_width}x{self.window_height}')
        
        # 设置窗口在屏幕右下角，避开任务栏
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        taskbar_height = 60
        x = screen_width - self.window_width - 10
        y = screen_height - self.window_height - taskbar_height - 20
        self.root.geometry(f'+{x}+{y}')
        
        # 设置提夫尼蓝背景色
        self.root.configure(bg='#81D8D0')
        
        # 使用导入的饮水时间表
        self.water_schedule = WATER_SCHEDULE
        
        # 创建系统托盘图标
        self._create_tray_icon()
        
        self._init_ui()
        self.check_time()
        
        # 绑定窗口事件
        self.root.protocol('WM_DELETE_WINDOW', self._on_closing)

    def _init_ui(self):
        # 创建当前时间标签
        self.time_label = tk.Label(
            self.root,
            text='当前时间',
            font=('微软雅黑', 14, 'bold'),
            bg='#81D8D0',
            fg='black'
        )
        self.time_label.pack(pady=10)
        
        # 创建一个框架来容纳按钮和标签
        self.info_frame = tk.Frame(self.root, bg='#81D8D0')
        self.info_frame.pack(pady=5)
        
        # 创建详情按钮
        self.detail_button = tk.Button(
            self.info_frame,
            text='📋',
            font=('微软雅黑', 12),
            bg='#6BC5BB',
            fg='black',
            relief='flat',
            command=self.show_schedule_details,
            width=2
        )
        self.detail_button.pack(side=tk.LEFT, padx=5)
        
        # 创建下一次饮水时间标签
        self.next_time_label = tk.Label(
            self.info_frame,
            text='下次饮水时间',
            font=('微软雅黑', 12, 'bold'),
            bg='#81D8D0',
            fg='black'
        )
        self.next_time_label.pack(side=tk.LEFT)
        
        # 添加喇叭按钮
        self.sound_button = tk.Button(
            self.info_frame,
            text='🔊',
            font=('微软雅黑', 12),
            bg='#6BC5BB',
            fg='black',
            relief='flat',
            command=lambda: generate_sound(self.sound_button),
            width=2
        )
        self.sound_button.pack(side=tk.LEFT, padx=5)

    def show_schedule_details(self):
        self.detail_button.configure(state='disabled')
        
        # 创建新窗口
        details_window = tk.Toplevel(self.root)
        details_window.title('饮水时间表')
        
        # 设置窗口大小和位置
        window_width = 1000  # 增加宽度以适应左右布局
        window_height = 600
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        details_window.geometry(f'{window_width}x{window_height}+{x}+{y}')
        details_window.configure(bg='#81D8D0')
        
        # 创建左右框架
        left_frame = tk.Frame(details_window, bg='#81D8D0')
        right_frame = tk.Frame(details_window, bg='#81D8D0')
        
        # 设置左右比例为 4:6
        details_window.grid_columnconfigure(0, weight=4)
        details_window.grid_columnconfigure(1, weight=6)
        details_window.grid_rowconfigure(0, weight=1)
        details_window.grid_rowconfigure(1, weight=0)  # 为关闭按钮添加行
        
        left_frame.grid(row=0, column=0, sticky='nsew', padx=10, pady=10)
        right_frame.grid(row=0, column=1, sticky='nsew', padx=10, pady=10)
        
        # 左侧：饮水时间表
        schedule_text = tk.Text(
            left_frame,
            font=('微软雅黑', 11),
            bg='#81D8D0',
            fg='black',
            relief='flat',
            wrap=tk.WORD,
            padx=10,
            pady=10,
            width=40  # 设置合适的宽度
        )
        schedule_text.pack(fill=tk.BOTH, expand=True)
        
        for time, desc in self.water_schedule.items():
            schedule_text.insert(tk.END, f'⏰ {time}\n{desc}\n\n')
        schedule_text.configure(state='disabled')
        
        # 右侧：身材管理分析
        # 创建标题
        title_label = tk.Label(
            right_frame,
            text="身体数据分析",
            font=('微软雅黑', 16, 'bold'),
            bg='#81D8D0',
            fg='black'
        )
        title_label.pack(pady=(0, 20))
        
        # 创建表单区域（使用Frame包装）
        form_container = tk.Frame(right_frame, bg='#81D8D0')
        form_container.pack(fill=tk.X, padx=30)
        
        # 创建输入字段
        entries = {}
        fields = [
            ('身高(cm)', '170'),
            ('体重(kg)', '65'),
            ('运动频率(次/周)', '3'),
        ]
        
        # 定义性别选项
        gender_options = ['男', '女']
        
        # 定义饮食偏好选项
        diet_preferences = [
            '均衡饮食',
            '高蛋白饮食',
            '低脂饮食',
            '生酮饮食',
            '素食主义',
            '地中海饮食',
            '间歇性断食'
        ]
        
        # 使用网格布局创建表单
        for i, (field, default) in enumerate(fields):
            row = i // 2
            col = i % 2
            
            # 创建每个字段的容器
            field_frame = tk.Frame(form_container, bg='#81D8D0')
            field_frame.grid(row=row, column=col, padx=10, pady=8, sticky='w')
            
            # 标签
            label = tk.Label(
                field_frame,
                text=field,
                width=12,
                anchor='w',
                font=('微软雅黑', 11),
                bg='#81D8D0',
                fg='black'
            )
            label.pack(side=tk.LEFT)
            
            # 输入框
            entry = tk.Entry(
                field_frame,
                width=15,
                font=('微软雅黑', 11),
                relief='solid',
                bd=1
            )
            entry.insert(0, default)
            entry.pack(side=tk.LEFT, padx=5)
            entries[field] = entry
        
        # 添加性别下拉菜单
        gender_frame = tk.Frame(form_container, bg='#81D8D0')
        gender_frame.grid(row=1, column=1, padx=10, pady=8, sticky='w')
        
        gender_label = tk.Label(
            gender_frame,
            text='性别',
            width=12,
            anchor='w',
            font=('微软雅黑', 11),
            bg='#81D8D0',
            fg='black'
        )
        gender_label.pack(side=tk.LEFT)
        
        # 创建性别下拉菜单
        gender_var = tk.StringVar(value=gender_options[0])
        gender_menu = tk.OptionMenu(
            gender_frame,
            gender_var,
            *gender_options
        )
        gender_menu.config(
            font=('微软雅黑', 11),
            bg='white',
            width=11,
            relief='solid',
            bd=1
        )
        gender_menu.pack(side=tk.LEFT, padx=5)
        entries['性别'] = gender_var
        
        # 添加饮食偏好下拉菜单
        diet_frame = tk.Frame(form_container, bg='#81D8D0')
        diet_frame.grid(row=2, column=0, padx=10, pady=8, sticky='w')
        
        diet_label = tk.Label(
            diet_frame,
            text='饮食偏好',
            width=12,
            anchor='w',
            font=('微软雅黑', 11),
            bg='#81D8D0',
            fg='black'
        )
        diet_label.pack(side=tk.LEFT)
        
        # 创建下拉菜单变量并设置默认值
        diet_var = tk.StringVar(value=diet_preferences[0])
        diet_menu = tk.OptionMenu(
            diet_frame,
            diet_var,
            *diet_preferences
        )
        diet_menu.config(
            font=('微软雅黑', 11),
            bg='white',
            width=11,
            relief='solid',
            bd=1
        )
        diet_menu.pack(side=tk.LEFT, padx=5)
        entries['饮食偏好'] = diet_var  # 存储变量而不是输入框
        
        # 创建按钮容器
        button_container = tk.Frame(right_frame, bg='#81D8D0')
        button_container.pack(pady=20)
        
        # 创建分析按钮
        analyze_button = tk.Button(
            button_container,
            text='开始分析',
            font=('微软雅黑', 12),
            bg='#6BC5BB',
            fg='black',
            relief='flat',
            padx=20,
            pady=5,
            command=lambda: analyze_body_data(entries, result_text, analyze_button)
        )
        analyze_button.pack()
        
        # 创建分割线
        separator = tk.Frame(right_frame, height=2, bg='#6BC5BB')
        separator.pack(fill=tk.X, padx=30, pady=20)
        
        # 创建结果显示区域
        result_container = tk.Frame(right_frame, bg='#81D8D0')
        result_container.pack(fill=tk.BOTH, expand=True, padx=30)
        
        result_label = tk.Label(
            result_container,
            text="分析结果",
            font=('微软雅黑', 14, 'bold'),
            bg='#81D8D0',
            fg='black'
        )
        result_label.pack(pady=(0, 10))
        
        # 创建结果显示区域
        result_text = tk.Text(
            result_container,
            font=('微软雅黑', 11),
            bg='white',
            fg='black',
            relief='solid',
            wrap=tk.WORD,
            padx=15,
            pady=15,
            height=6
        )
        result_text.pack(fill=tk.BOTH, expand=True)
        result_text.insert(tk.END, "分析结果将在这里显示...")
        result_text.configure(state='disabled')
        
        def analyze_data(entries, result_text):
            # 收集表单数据并构建info对象
            info = {
                "身高": f"{entries['身高(cm)'].get()}cm",
                "体重": f"{entries['体重(kg)'].get()}kg",
                "性别": entries['性别'].get(),
                "运动频率": f"{entries['运动频率(次/周)'].get()}次/周",
                "饮食偏好": entries['饮食偏好'].get()
            }
            
            # 创建加载提示
            result_text.configure(state='normal')
            result_text.delete(1.0, tk.END)
            result_text.insert(tk.END, "分析中，请稍候...")
            result_text.configure(state='disabled')
            
            def api_call():
                try:
                    # 调用AI接口
                    from webAPI.Get_Qwen import Get_Qwen
                    qwen = Get_Qwen()
                    result = qwen.get_api(info)
                    
                    # 使用after方法在主线程中更新UI
                    def update_result():
                        result_text.configure(state='normal')
                        result_text.delete(1.0, tk.END)
                        result_text.insert(tk.END, result)
                        result_text.configure(state='disabled')
                    
                    # 在主线程中更新UI
                    result_text.after(0, update_result)
                    
                except Exception as e:
                    # 在主线程中显示错误
                    result_text.after(0, lambda: messagebox.showerror("错误", f"分析过程出现错误：{str(e)}"))
            
            # 创建并启动线程
            import threading
            thread = threading.Thread(target=api_call)
            thread.daemon = True  # 设置为守护线程
            thread.start()
        
        # 添加关闭按钮
        # 修改关闭按钮的布局方式
        close_button = tk.Button(
            details_window,
            text='关闭',
            font=('微软雅黑', 10),
            bg='#6BC5BB',
            fg='black',
            command=lambda: self._on_details_close(details_window)
        )
        # 使用 grid 替代 pack
        close_button.grid(row=1, column=0, columnspan=2, pady=10)
        
        details_window.protocol("WM_DELETE_WINDOW", lambda: self._on_details_close(details_window))

    def _on_details_close(self, window):
        # 启用详情按钮
        self.detail_button.configure(state='normal')
        # 关闭详情窗口
        window.destroy()

    def check_time(self):
        times = get_formatted_time()
        self.time_label.config(text=f'{times["full_time"]}')
        
        next_time = get_next_water_time(self.water_schedule, times['check_time'])
        self.next_time_label.config(text=f'下次饮水: {next_time}')
        
        if times['check_time'] in self.water_schedule:
            sound = generate_sound()
            messagebox.showinfo('饮水提醒', self.water_schedule[times['check_time']])
        
        self.root.after(1000, self.check_time)
    
    def _create_tray_icon(self):
        # 创建托盘图标菜单
        menu = pystray.Menu(
            pystray.MenuItem('显示', self._show_window),
            pystray.MenuItem('隐藏', self._hide_window),
            pystray.MenuItem('退出', self._quit_window)
        )
        
        # 创建托盘图标
        icon_path = os.path.join(os.path.dirname(__file__), 'assets', 'icon.png')
        if not os.path.exists(icon_path):
            icon_path = os.path.join(os.path.dirname(__file__), 'gitcode', 'DrinkingWaterTips', 'assets', 'icon.png')
        image = Image.open(icon_path)
        self.icon = pystray.Icon('饮水小贴士', image, '饮水小贴士', menu)
        
        # 在单独的线程中运行托盘图标
        import threading
        icon_thread = threading.Thread(target=self.icon.run)
        icon_thread.daemon = True
        icon_thread.start()
    
    def _show_window(self, icon, item):
        self.root.deiconify()
        self.root.lift()
        self.root.focus_force()
    
    def _hide_window(self, icon, item):
        self.root.withdraw()
    
    def _quit_window(self, icon, item):
        # 停止托盘图标
        self.icon.stop()
        # 销毁主窗口
        self.root.quit()
        self.root.destroy()
    
    def _on_closing(self):
        self.root.withdraw()
    
    def run(self):
        self.root.mainloop()

if __name__ == '__main__':
    app = WaterReminder()
    app.run()